package com.winchain.chainbill.trade.cmd;

import com.shell.bee.acct.account.po.AcctBas;
import com.shell.bee.acct.account.service.AcctBasService;
import com.shell.bee.acct.transaction.po.AcctTxRec;
import com.shell.bee.sequence.SequenceHelper;
import com.shell.framework.command.CallbackContext;
import com.shell.framework.command.ICallback;
import com.winchain.chainbill.basic.cus.po.CusRec;
import com.winchain.chainbill.basic.cus.service.CusRecService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.util.StringUtil;

@Component
public class AcctBasCmd<T> implements ICallback<T, AcctTxRec> {
	@Autowired
	CusRecService basCusService;
	@Autowired
	AcctBasService AcctBasService;

	public boolean callback(CallbackContext<T, AcctTxRec> context) throws Exception {
		AcctTxRec tx = (AcctTxRec) context.getTarget();
		String optType = tx.getOptType();
		String txType = tx.getTxType();
		String txAcctNo = tx.getTxAcctNo();
		String cpAcctNo = tx.getCpAcctNo();
		if (("qt_snd".equals(optType)) && ("qt_credit".equals(txType))) {
			AcctBas entity = (AcctBas) this.AcctBasService.selectByKey(cpAcctNo);
			String acctAlias = entity.getAcctAlias();
			if (StringUtil.isEmpty(acctAlias)) {
				CusRec txCus = this.basCusService.findCustomerByAcctNo(txAcctNo);
				CusRec cpCus = this.basCusService.findCustomerByAcctNo(cpAcctNo);
				String creditCode = getCreditCode(txCus.getCusCode(), cpCus.getCusCode(), 4);
				entity.setAcctAlias(creditCode);
				this.AcctBasService.saveOrUpdate(entity);
			}
		}
		return false;
	}

	public String getCreditCode(String sourceCode, String targetCode, int length) {
		return sourceCode + targetCode
				+ SequenceHelper.generateCode(new StringBuilder().append("SX_").append(sourceCode).toString(), length);
	}
}
